<?php
/*
Plugin Name: Real-time Online Users
Plugin URI: http://pages.usherbrooke.ca/mel
Description: Shows real time online users.
Author: Mahdi El Masaoudi
Version: 1.0.2
Author URI: https://www.linkedin.com/profile/view?id=51455976&
*/

/* Enable sessions */
function init_sessions() {
    if (!session_id()) {
        session_start();
    }
}
add_action('init', 'init_sessions');

/* load installation scripts */
require_once(dirname(__FILE__)."/install.php");


register_activation_hook(__FILE__,"rtou_install");
register_deactivation_hook(__FILE__,"rtou_uninstall");


function rtou_widget_init(){
	register_widget('rtou_Widget');
}

add_action('widgets_init','rtou_widget_init');


/* Register Actions */
add_action('wp_ajax_rtou_refresh_online', 'doRefreshOnlineUsers');
add_action('wp_ajax_nopriv_rtou_refresh_online', 'doRefreshOnlineUsers');
add_action('wp_ajax_rtou_refresh_registred', 'doRefreshRegistredUsers');
add_action('wp_ajax_nopriv_rtou_refresh_registred', 'doRefreshRegistredUsers');
add_action('wp_ajax_rtou_refresh_guests', 'doRefreshGuestUsers');
add_action('wp_ajax_nopriv_rtou_refresh_guests', 'doRefreshGuestUsers');
add_action('wp_ajax_rtou_refresh_list', 'doRefreshListUsers');
add_action('wp_ajax_nopriv_rtou_refresh_list', 'doRefreshListUsers');
add_action('wp_ajax_rtou_update', 'doUpdate');
add_action('wp_ajax_nopriv_rtou_update', 'doUpdate');

/*
* ajax Callback to get number of online users
*/
function doRefreshOnlineUsers(){
	global $wpdb;
	$delay = addslashes($_REQUEST['delay']);
	$timestamp = time();
	$sql="SELECT count(*) FROM ".$wpdb->prefix."rtou WHERE $timestamp - lastseen <= $delay";
	$n=$wpdb->get_var(($sql));
	die($n);
}

/*
* ajax Callback to get number of online registred users
*/
function doRefreshRegistredUsers(){
	global $wpdb;
	$delay = addslashes($_REQUEST['delay']);
	$timestamp = time();
	$sql="SELECT count(*) FROM ".$wpdb->prefix."rtou WHERE registred=1 AND $timestamp - lastseen <= $delay";
	$n=$wpdb->get_var(($sql));
	die($n);
}

/*
* ajax Callback to get number of online guest users
*/
function doRefreshGuestUsers(){
	global $wpdb;
	$delay = addslashes($_REQUEST['delay']);
	$timestamp = time();
	$sql="SELECT count(*) FROM ".$wpdb->prefix."rtou WHERE registred=0 AND $timestamp - lastseen <= $delay";
	$n=$wpdb->get_var(($sql));
	die($n);
}

/*
* ajax Callback to get the list of users
*/
function doRefreshListUsers(){
	global $wpdb;
	$delay = addslashes($_REQUEST['delay']);
	$timestamp = time();
	$sql="SELECT * FROM ".$wpdb->prefix."rtou WHERE registred=1 AND $timestamp - lastseen <= $delay";
	$ret="";
	$results=$wpdb->get_results($sql);
	foreach($results as $result){
		$ret.='<span id="user_list_element"> '.$result->username.' </span>';
	}
	
	die($ret);
}

/*
* ajax Callback to update users data
*/
function doUpdate(){
	global $wpdb;
	$username = addslashes($_REQUEST['username']);
	$registred = addslashes($_REQUEST['registred']);
	$lastseen = addslashes($_REQUEST['lastseen']);
	$sql="SELECT * FROM ".$wpdb->prefix."rtou WHERE username='$username'";
	if($wpdb->query($sql)){
		$sql="UPDATE ".$wpdb->prefix."rtou SET lastseen='$lastseen' WHERE username='$username'";
		$wpdb->query($sql);
	}else{
		$sql="INSERT INTO ".$wpdb->prefix."rtou(username,registred,lastseen) VALUES('$username',$registred,'$lastseen')";
		$wpdb->query($sql);
	}
	die($sql);
}

/* Enable ajax calls on frontend */
function frontend_ajaxurl() {
?>
<script type="text/javascript">var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';</script>
<?php
}
add_action('wp_head','frontend_ajaxurl');

/* The Widget */
class rtou_Widget extends WP_Widget {
	function rtou_Widget() {
		$widget_options=array(
			'classname'=>'rtou_Widget',
			'description'=>'Shows real time online users.'
							);
		parent::WP_Widget('rtou_Widget','Real-Time Online Users',$widget_options);
	}

	function form($instance) {
		$this->includeLangFile();
		$title = isset( $instance['title']) ? esc_attr( $instance['title'] ) : '';
		$delay = isset( $instance['delay']) ? esc_attr( $instance['delay'] ) : '';
		$show_online_users = isset( $instance['show_online_users']) ? esc_attr( $instance['show_online_users'] ) : '';
		$show_registred_users = isset( $instance['show_registred_users']) ? esc_attr( $instance['show_registred_users'] ) : '';
		$show_guests = isset( $instance['show_guests']) ? esc_attr( $instance['show_guests'] ) : '';
		$show_list_users = isset( $instance['show_list_users']) ? esc_attr( $instance['show_list_users'] ) : '';
		?>
		<label for="<?php echo $this->get_field_id('title');?>">
		<?php echo TITLE;?> : <br/>
		<input type="text" id="<?php echo $this->get_field_id('title');?>" name="<?php echo $this->get_field_name('title');?>" value="<?php echo esc_attr($instance['title']);?>" />
		</label>
		<br/>
		<label for="<?php echo $this->get_field_id('delay');?>">
		<?php echo DELAY;?> : <br/>
		<input type="text" id="<?php echo $this->get_field_id('delay');?>" name="<?php echo $this->get_field_name('delay');?>" value="<?php echo esc_attr($instance['delay']);?>" /> (s)
		</label>
		<br/>
		<fieldset><label><?php echo VIEW_OPTIONS;?></label>
		<br/>
		<input type="checkbox" id="<?php echo $this->get_field_id('show_online_users');?>" name="<?php echo $this->get_field_name('show_online_users');?>" value="1" <?php if($show_online_users==1){echo 'checked';}?> /> 
		&nbsp;<?php echo ONLINE_USERS;?>
		
		<br/>
		<input type="checkbox" id="<?php echo $this->get_field_id('show_registred_users');?>" name="<?php echo $this->get_field_name('show_registred_users');?>" value="1" <?php if($show_registred_users==1){echo 'checked';}?> /> 
		&nbsp;<?php echo REGISTRED_USERS;?>
		
		<br/>
		<input type="checkbox" id="<?php echo $this->get_field_id('show_guests');?>" name="<?php echo $this->get_field_name('show_guests');?>" value="1" <?php if($show_guests==1){echo 'checked';}?> /> 
		&nbsp;<?php echo GUEST_USERS;?>
		
		<br/>
		<input type="checkbox" id="<?php echo $this->get_field_id('show_list_users');?>" name="<?php echo $this->get_field_name('show_list_users');?>" value="1" <?php if($show_list_users==1){echo 'checked';}?> /> 
		&nbsp;<?php echo CONNECTED_USERS;?>
		</fieldset>
		
		<?php
		
	}

	function update($new_instance, $old_instance) {
		$this->includeLangFile();
		$instance = $old_instance;
		$instance['title'] = strip_tags($new_instance['title']);
		$instance['delay'] = strip_tags($new_instance['delay']);
		$instance['show_online_users'] = strip_tags($new_instance['show_online_users']);
		$instance['show_registred_users'] = strip_tags($new_instance['show_registred_users']);
		$instance['show_guests'] = strip_tags($new_instance['show_guests']);
		$instance['show_list_users'] = strip_tags($new_instance['show_list_users']);
		return $instance;
	}

	function widget($args, $instance) {
		$this->includeLangFile();
		extract($args,EXTR_SKIP);
		$title=isset($instance["title"])?$instance["title"]:"";
		$delay=isset($instance["delay"])?$instance["delay"]:"";
		$delay=is_numeric($delay)?$delay:10;
		$show_online_users=isset($instance["show_online_users"])?$instance["show_online_users"]:"";
		$show_registred_users=isset($instance["show_registred_users"])?$instance["show_registred_users"]:"";
		$show_guests=isset($instance["show_guests"])?$instance["show_guests"]:"";
		$show_list_users=isset($instance["show_list_users"])?$instance["show_list_users"]:"";
		
		
		global $wpdb;
		$username='';
		$timestamp=time();
		$registred=0;
		if ( is_user_logged_in() ) {
			$registred=1;
			$current_user = wp_get_current_user();
			$username=$current_user->user_login;
			$sql="SELECT * FROM ".$wpdb->prefix."rtou WHERE username='$username'";
			if($wpdb->query($sql)){
				$sql="UPDATE ".$wpdb->prefix."rtou SET lastseen='$timestamp' WHERE username='$username'";
				$wpdb->query($sql);
			}else{
				$sql="INSERT INTO ".$wpdb->prefix."rtou(username,registred,lastseen) VALUES('$username',1,'$timestamp')";
				$wpdb->query($sql);
			}
		} else {
			$registred=0;
			if(!isset($_SESSION['unregistredId']) || empty($_SESSION['unregistredId'])){
				$_SESSION['unregistredId']= rand(1000,20000) * rand (1000,20000);
			}
			$username=$_SESSION['unregistredId'];
			$sql="SELECT * FROM ".$wpdb->prefix."rtou WHERE username='$username'";
			if($wpdb->query($sql)){
				$sql="UPDATE ".$wpdb->prefix."rtou SET lastseen='$timestamp' WHERE username='$username'";
				$wpdb->query($sql);
			}else{
				$sql="INSERT INTO ".$wpdb->prefix."rtou(username,registred,lastseen) VALUES('$username',0,'$timestamp')";
				$wpdb->query($sql);
			}	
		}
		
		
		echo $before_widget;
		echo $before_title.$title.$after_title;
		?>
		<script>
		if(typeof $ == 'undefined'){
				// wp_enqueu_script can not be used here because we can not check in php if jQuery is available
				document.write('<script type="text/javascript" src="<?php echo get_option("siteurl")."/wp-content/plugins/rtou_widget";?>/js/jquery-1.7.1.min.js"></'+'script>');
				if(typeof jQuery != 'undefined')
					$=jQuery;
		}
		</script>
		<div id="rtou_widget">
		<?php if($show_online_users==1){ ?>
		<p><img src="<?php echo get_option("siteurl").'/wp-content/plugins/rtou_widget/images/online_icon.png';?>" />&nbsp;<span id="div_online_users">0</span> &nbsp;<?php echo NB_ONLINE_USERS;?></p>
		<?php } ?>
		<?php if($show_registred_users==1){ ?>
		<p><img src="<?php echo get_option("siteurl").'/wp-content/plugins/rtou_widget/images/registred_icon.png';?>" />&nbsp;<span id="div_registred_users">0</span>&nbsp;<?php echo NB_REGISTRED_USERS;?></p>
		<?php } ?>
		<?php if($show_guests==1){ ?>
		<p><img src="<?php echo get_option("siteurl").'/wp-content/plugins/rtou_widget/images/guest_icon.png';?>" />&nbsp;<span id="div_guest_users">0</span>&nbsp;<?php echo NB_GUEST_USERS;?></p>
		<?php } ?>
		<?php if($show_list_users==1){ ?>
		<p><div id="div_list_users"></div></p>
		<?php } ?>
		
		<script>
		// first call
		if(typeof updateUsersData == 'function') updateUsersData();
		if(typeof getOnlineUsers == 'function') getOnlineUsers();
		if(typeof getRegistredUsers == 'function') getRegistredUsers();
		if(typeof getGuests == 'function') getGuests();
		if(typeof getListUsers == 'function') getListUsers();
		
		
		function updateUsersData(){
			var url = ajaxurl;
			var d=new Date();
			var t=d.getTime();
				$.ajax({
					type: 'POST',
					url: ajaxurl,
					data: { action: "rtou_update",
							username: "<?php echo $username;?>",
							registred: "<?php echo $registred;?>",
							lastseen: Math.round(t/1000)},
					success: function(data) {

					}

				});
		};
		
		setInterval(updateUsersData,<?php echo $delay * 1000;?>);
		<?php if($show_online_users==1){ ?>
		function getOnlineUsers(){			
			var url = ajaxurl;
				$.ajax({
					type: 'POST',
					url: ajaxurl,
					data: { action: "rtou_refresh_online",
							delay: "<?php echo $delay;?>"
							},
					success: function(data) {
						$('#div_online_users').html(data);
					}

				});
		};
		setInterval(getOnlineUsers,<?php echo $delay * 1000;?>);
		<?php } ?>
		<?php if($show_registred_users==1){ ?>
		function getRegistredUsers(){			
			var url = ajaxurl;
				$.ajax({
					type: 'POST',
					url: ajaxurl,
					data: { action: "rtou_refresh_registred",
							delay: "<?php echo $delay;?>"
							},
					success: function(data) {
						$('#div_registred_users').html(data);
					}

				});
		};
		setInterval(getRegistredUsers,<?php echo $delay * 1000;?>);
		<?php } ?>
		<?php if($show_guests==1){ ?>
		function getGuests(){			
			var url = ajaxurl;
				$.ajax({
					type: 'POST',
					url: ajaxurl,
					data: { action: "rtou_refresh_guests",
							delay: "<?php echo $delay;?>"
							},
					success: function(data) {
						$('#div_guest_users').html(data);
					}

				});
		};
		setInterval(getGuests,<?php echo $delay * 1000;?>);
		<?php } ?>
		<?php if($show_list_users==1){ ?>
		function getListUsers(){			
			var url = ajaxurl;
				$.ajax({
					type: 'POST',
					url: ajaxurl,
					data: { action: "rtou_refresh_list",
							delay: "<?php echo $delay;?>"
							},
					success: function(data) {
						$('#div_list_users').html(data);
					}

				});
		};
		setInterval(getListUsers,<?php echo $delay * 1000;?>);
		
		<?php } ?>
		</script>
		</div>
		<?php
		echo $after_widget;
	}
	
	/* Including language file */
	function includeLangFile(){	
		switch (WPLANG){
				case 'fr_FR':
					require_once(dirname(__FILE__)."/lang/lang_fr.php");
					break;
				case 'en_EN':
					require_once(dirname(__FILE__)."/lang/lang_en.php");
					break;
				case 'ru_RU':
					require_once(dirname(__FILE__)."/lang/lang_ru.php");
					break;
				default:
					require_once(dirname(__FILE__)."/lang/lang_en.php");
					break;
		}
	}
	
}

?>
